package com.itheima.service.backend.impl;

import com.itheima.dto.OrderSettingDTO;
import com.itheima.common.utils.DateUtils;
import com.itheima.mapper.backend.OrdersettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.backend.OrdersettingService;
import com.itheima.vo.OrderSettingVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 预约设置服务实现类
 */
@Service
@Slf4j
public class OrdersettingServiceImpl implements OrdersettingService {

    @Autowired
    private OrdersettingMapper ordersettingMapper;

    /**
     * 下载Excel模板文件
     * @param response
     */
    @Override
    public void download(HttpServletResponse response) {
        //设置响应内容类型为excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //提供Excel模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入Excel数据到数据库
     * @param excelFile
     * @throws Exception
     */
    @Override
    public void saveExcelDataToDatabase(MultipartFile excelFile) throws Exception {
        InputStream inputStream = excelFile.getInputStream();//获取文件输入流
        Workbook workbook = WorkbookFactory.create(inputStream);// 创建工作簿
        Sheet sheet = workbook.getSheetAt(0);// 获取第一个工作表
        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过标题行
            Date orderDate = row.getCell(0).getDateCellValue();
            int number = (int) row.getCell(1).getNumericCellValue();
            // 插入或更新数据库
            if (ordersettingMapper.findByOrderDate(orderDate) == null) {
                ordersettingMapper.addNumberByOrderDate(orderDate, number);
            } else {
                ordersettingMapper.editByOrderDate(orderDate, number);
            }
        }
    }

    /**
     * 根据月份查询预约设置数据
     * @param month
     * @return
     */
    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) throws Exception {
        // 使用自定义格式 yyyy-M 解析单/双位月份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M");
        YearMonth yearMonth = YearMonth.parse(month, formatter);

        // 获取当月第一天和最后一天 LocalDate
        LocalDate firstDayOfMonthLD = yearMonth.atDay(1);
        LocalDate lastDayOfMonthLD = yearMonth.atEndOfMonth();

        // 转换为 Date 类型（当天 00:00）
        Date firstDayOfMonth = Date.from(firstDayOfMonthLD.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date lastDayOfMonth = Date.from(lastDayOfMonthLD.atStartOfDay(ZoneId.systemDefault()).toInstant());

        // 查询数据库数据
        List<OrderSetting> orderSettingList = ordersettingMapper.getOrderSettingByMonth(firstDayOfMonth, lastDayOfMonth);

        // 构建 VO 列表
        List<OrderSettingVO> orderSettingVOList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingList) {
            String dateString = DateUtils.parseDate2String(orderSetting.getOrderDate(), "dd");
            orderSettingVOList.add(new OrderSettingVO(dateString, orderSetting.getNumber(), orderSetting.getReservations()));
        }

        return orderSettingVOList;
    }

    /**
     * 根据预约日期设置每天可预约人数
     * @param orderSettingDTO
     * @return
     */
    @Override
    public void editNumberByOrderDate(OrderSettingDTO orderSettingDTO) throws Exception {

        Date orderDate = DateUtils.parseString2Date(orderSettingDTO.getOrderDate());
        Integer number = orderSettingDTO.getNumber();

        OrderSetting o = ordersettingMapper.findByOrderDate(orderDate);

        if ( o == null) {
            ordersettingMapper.addNumberByOrderDate(orderDate, number);
        } else {
            ordersettingMapper.editByOrderDate(orderDate, number);
        }
    }
}
